using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using HyperLocal.Core;
using HyperLocal.Service;
using System.IO;

namespace HyperLocal.MVC.Controllers
{
    public class ProfileController : Controller
    {
        //
        // GET: /Profile/
        [Authorize]
        public ActionResult Index()
        {
            Repository repo = ConnectionService.getRepository;
            var user = repo.First<LocalOrbUser>(x => x.UserName == User.Identity.Name);

            ViewData.Add("CurrentUser", user);

            return View();
        }

                //
        // GET: /Profile/
        [Authorize]
        public ActionResult ProfileImage()
        {
            Repository repo = ConnectionService.getRepository;
            var user = repo.First<LocalOrbUser>(x => x.UserName == User.Identity.Name);
            return View(user);
        }

        //
        // GET: /Profile/Details/5
        [Authorize]
        public ActionResult Details(Guid id)
        {
            return View();
        }

        //
        // GET: /Profile/Create
        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Profile/Create
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            Repository repo = ConnectionService.getRepository;
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Profile/Edit/5
        [Authorize]
        public ActionResult Edit(Guid id)
        {
            Repository repo = ConnectionService.getRepository;
            var user = repo.First<LocalOrbUser>(x => x.LocalOrbUserId == id);

            return View(user);
        }

        //
        // POST: /Profile/Edit/5
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Guid id, FormCollection collection)
        {

            Repository repo = ConnectionService.getRepository;
            var user = repo.First<LocalOrbUser>(x => x.LocalOrbUserId == id);

            if (!validEditCollection(collection))
            {
                return View(user);
            }


            try
            {

                string sFileName = collection["ProfileImageLocation"];
                var file = Request.Files["ProfileImageLocation"];
                //'file' is always null, and Request.Files.Count is always 0 ???
                if (file != null)
                {
                    byte[] buf = new byte[file.ContentLength];
                    file.InputStream.Read(buf, 0, file.ContentLength);
                    //do stuff with the bytes

                    user.LocalOrbProfiles[0].ProfileImage = buf;
                }

                repo.Update<LocalOrbUser>(user);

                return RedirectToAction("Index");

            }
            catch
            {
                return View(user);
            }
        }

        private bool validEditCollection(FormCollection collection)
        {
                        bool valid = true;

            if (string.IsNullOrEmpty(collection["FirstName"]))
            {
                ModelState.AddModelError("_FORM", "First Name Missing");
                valid = false;
            } 

            return valid;
        }

        [Authorize]
        public ActionResult ChooseCommunity()
        {
            return View();
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChooseCommunity(FormCollection collection)
        {
            if (!validCollection(collection))
            {
                return View();
            }

            Repository repo = ConnectionService.getRepository;

            //Get the current User
            var currentUser =
                repo.First<LocalOrbUser>(x => x.UserName.ToUpper() == User.Identity.Name.ToUpper());

            //Update the community
            var comunity =
                repo.First<LocalOrbCommunity>(x => Convert.ToInt32(x.ZipCode) == Convert.ToInt32(collection["ActualZipCode"]));
            currentUser.LocalOrbCommunity = comunity;

            //Update/Create the address
            if (currentUser.LocalOrbUserAddresses.Count<LocalOrbUserAddress>() == 0)
            {
                currentUser.LocalOrbUserAddresses.Add(new LocalOrbUserAddress()
                {
                    DateCreated = DateTime.Now,
                    DateLastModified = DateTime.Now,
                    Deleted = false,
                    Active = true,
                    Accuracy = Convert.ToInt32(collection["Accuracy"]),
                    City = collection["City"],
                    State = collection["State"],
                    Latitude = Convert.ToDouble(collection["Latitude"]),
                    Longitude = Convert.ToDouble(collection["Longitude"]),
                    FullAddress = collection["Address"],
                    LocalOrbUserAddressId = Guid.NewGuid(),
                    Zip = collection["ActualZipCode"]
                });
            }
            else
            {
                var currentAddress = currentUser.LocalOrbUserAddresses.First<LocalOrbUserAddress>();

                currentAddress.DateLastModified = DateTime.Now;
                currentAddress.Accuracy = Convert.ToInt32(collection["Accuracy"]);
                currentAddress.Longitude = Convert.ToDouble(collection["Longitude"]);
                currentAddress.Latitude = Convert.ToDouble(collection["Latitude"]);
                currentAddress.City = collection["City"];
                currentAddress.State = collection["State"];
                currentAddress.FullAddress = collection["Address"];
                currentAddress.Zip = collection["ActualZipCode"];
            }

            //Refresh the database entity
            repo.Update<LocalOrbUser>(currentUser);

            return RedirectToAction("Index");
        }

        /// <summary>
        /// Validates the Collection contains all of the require
        /// Information
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        private bool validCollection(FormCollection collection)
        {
            bool valid = true;

            if (string.IsNullOrEmpty(collection["ActualZipCode"]))
            {
                ModelState.AddModelError("_FORM", "Actual Zip Code Missing");
                valid = false;
            }

            if (string.IsNullOrEmpty(collection["Accuracy"]))
            {
                ModelState.AddModelError("_FORM", "Accuracy Missing");
                valid = false;
            }

            if (string.IsNullOrEmpty(collection["Longitude"]))
            {
                ModelState.AddModelError("_FORM", "Longitude Missing");
                valid = false;
            }
            if (string.IsNullOrEmpty(collection["Latitude"]))
            {
                ModelState.AddModelError("_FORM", "Latitude Missing");
                valid = false;
            }
            if (string.IsNullOrEmpty(collection["City"]))
            {
                ModelState.AddModelError("_FORM", "City Missing");
                valid = false;
            }
            if (string.IsNullOrEmpty(collection["State"]))
            {
                ModelState.AddModelError("_FORM", "State Missing");
                valid = false;
            }
            if (string.IsNullOrEmpty(collection["Address"]))
            {
                ModelState.AddModelError("_FORM", "Address Missing");
                valid = false;
            }

            return valid;

        }
    }
}
